/*
 * @Author: wusd
 * @Date: 2022-06-15 09:39:58
 * @LastEditors: wusd
 * @LastEditTime: 2022-06-15 13:59:45
 * @Description:
 *
 */
import axios from 'axios'
import store from '@/store'
import { Loading, Message } from 'element-ui'
import { ElLoadingComponent } from 'element-ui/types/loading'
import { AnyObj } from 'types/common'

let loading: ElLoadingComponent
function startLoading() {
  //使用Element loading-start 方法
  loading = Loading.service({
    target: document.querySelector('#content') as HTMLElement,
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

function endLoading() {
  //使用Element loading-close 方法
  loading.close()
}
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
// 创建一个axios实例
const service = axios.create({
  // 请求超时时间
  timeout: 3000,
  baseURL: '/credit'
})

// 添加请求拦截器
service.interceptors.request.use(
  (config: AnyObj) => {
    if (store.state.user.token && !config.url.includes('http')) {
      // 添加token
      config.headers.token = store.state.user.token
      // 关闭请求缓存
      config.headers['Cache-Control'] = 'no-cache'
      config.headers['Pragma'] = 'no-cache'
    }
    showFullScreenLoading()
    return config
  },
  err => {
    console.log(err)
  }
)

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const data = response.data
      if (data.code && ![2000, 4002].includes(data.code)) {
        Message.error(data.message)
      }
      tryHideFullScreenLoading()
      return data
    }
    return response
  },
  err => {
    tryHideFullScreenLoading()
    console.log(err)
  }
)

export default service
